package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.CommentMapper;
import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDto;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo/")
public class WeiboController {
    @Autowired
    WeiboMapper mapper;

    @RequestMapping("insert")
    public int insert(@RequestBody WeiboDto weiboDto, HttpSession session) {
        //获取当前页面会话中的登录的用户对象
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return 2;
        }
        //向数据库存储数据,使用entity,将pojo.dto内容用BeanUtils拷贝出来
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDto, weibo);
        //给weibo对象的其它属性赋值
        weibo.setUserId(user.getId());//设置当前登录的用户id为微博的作者id
        weibo.setCreated(new Date());//设置当前时间为发布微博的时间
        System.out.println("weibo=" + weibo);
        mapper.insert(weibo);
        return 1;
    }

    @RequestMapping("select")
    public List<WeiboIndexVo> select() {
        return mapper.select();
    }

    @RequestMapping("selectById")
    public WeiboDetailVo selectById(int id) {
        return mapper.selectById(id);
    }

    @RequestMapping("select/mine")
    public ResultVo selectMine(HttpSession session) {
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return new ResultVo(2, "用户未登录", null);
        }
        //如果没有发过微博响应的会是一个空集合 客户端接收到之后也是一个空字符串
        return new ResultVo(1, "请求成功", mapper.selectMine(user.getId()));
    }

    @Autowired
    CommentMapper commentMapper;
    @RequestMapping("delete")
    public void delete(int id){
        //删除相关评论
        commentMapper.deleteByWeiboId(id);
        //删除微博
        mapper.deleteById(id);
    }
}
